package com.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class ProxyUtil {



    /**
     * 获得Dao的代理类
     * @param target
     * @return
     */
    public  static Object getDaoProxy(final Object target){


        Class[] interfaces =  target.getClass().getInterfaces();


        Object proxy =    Proxy.newProxyInstance(target.getClass().getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ThreadLocal<Connection> connectionThreadLocal =   SingletonThreadLocal.getInstance().getThreadLocal();//得到一个ThreadLocal对象

                Connection connection = null;
                try {
                    connection = JdbcUtil.getConnection();
                    connection.setAutoCommit(false);
                   /// 
                    connectionThreadLocal.set(connection);//从JdbcUtil中获得一个Connection对象
                    Object retuVal = method.invoke(target, args);//调用被代理对象的方法 调用saveOrder方法
                    connection.commit();
                    return  retuVal;
                }catch (Exception e){
                    connection.rollback();
                    throw e;
                }finally {
                    connection.close();
                }
            }
        });
        return  proxy;
    }
}
